﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Ymatou.CommonService;
using Ymt.Repository;
using YmtRpc.Domain;
using YmtRpc.Domain.Enum;
using Newtonsoft.Json;
namespace YmtRpc.Domain
{

    public class ServiceMetadataRepository : MySQLRepository<ServiceMetadata>, IServiceMetadataRepository
    {
        public ServiceMetadataRepository()
            : base()
        {

        }

        /// <summary>
        /// 获取服务元数据列表
        /// </summary>
        /// <returns></returns>
        public List<ServiceMetadata> GetList(string appId)
        {
            List<ServiceMetadata> list = new List<ServiceMetadata>();
            string sql = "select * from servicemetadata";
            ParametersWrapper par = new ParametersWrapper();

            if (!string.IsNullOrEmpty(appId))
            {
                sql += " WHERE AppId = @AppId";

                par.Add("AppId", appId);
            }

            var result = Query(sql, par.Build());
            if (result != null && result.Any())
            {
                list = result.ToList();
            }

            return list;
        }

        /// <summary>
        /// 获取应用程序列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetAppList()
        {
            List<ServiceMetadata> list = new List<ServiceMetadata>();

            string sql = "select DISTINCT AppId from servicemetadata";
            ParametersWrapper par = new ParametersWrapper();

            var result = Query(sql, par.Build());
            if (result != null && result.Any())
            {
                list = result.ToList();
            }

            return list.Select(r=>r.AppId).ToList();
        }


        public ServiceMetadata GetServiceMetadata(string appId, string apiName, string httpMethod)
        {
            return base.First(new { AppId = appId, ApiName = apiName, HttpMethod = httpMethod });
        }

        public bool TryInsert(ServiceMetadata entity)
        {
            try
            {
                if (entity == null)
                    return false;
                
                //ApplicationLog.Debug(string.Format("新增服务元数据；AppId: {0}, ApiName: {1}, HttpMethod: {2}", entity.AppId, entity.ApiName, entity.HttpMethod));
                this.Insert(entity);

                ApplicationLog.Info(string.Format("RpcAdmin,ServiceMetadata,Insert:{0}",JsonConvert.SerializeObject(entity)));
                return true;
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("新增服务元数据异常：{0}", ex.Message), ex);
                return false;
            };
        }

        public bool TryUpdate(ServiceMetadata entity)
        {
            try
            {
                if (entity == null)
                    return false;
                //ApplicationLog.Debug(string.Format("更新服务元数据；AppId: {0}, ApiName: {1}, HttpMethod: {2}", entity.AppId, entity.ApiName, entity.HttpMethod));
                
                IDictionary<string, object> updateColumns = new Dictionary<string, object>(){
                    {"Host", entity.Host },
                    {"ApiPath", entity.ApiPath },
                    {"LastUpdateTime", DateTime.Now },
                    {"Description", entity.Description },
                    {"Owner", entity.Owner },
                    {"LastUpdateTicks", DateTime.Now.Ticks }
                };

                IDictionary<string, object> where = new Dictionary<string, object>(){
                    {"AppId", entity.AppId },
                    {"ApiName", entity.ApiName },
                    {"HttpMethod", entity.HttpMethod }
                };

                int updateResult = this.Update(updateColumns, where);
                ApplicationLog.Info(string.Format("RpcAdmin,ServiceMetadata,Update:{0}", JsonConvert.SerializeObject(entity)));
                return updateResult > 0;
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("更新服务元数据异常：{0}", ex.Message), ex);
                return false;
            }
        }


        public bool Delete(string appId, string apiName, string httpMethod)
        {
            ApplicationLog.Debug(string.Format("删除服务元数据；AppId: {0}, ApiName: {1}, HttpMethod: {2}", appId, apiName, httpMethod));

            string sql = "DELETE FROM servicemetadata WHERE AppId = @AppId AND ApiName = @ApiName AND HttpMethod = @HttpMethod";

            Dictionary<string, object> par = new Dictionary<string, object>();
            par.Add("AppId", appId);
            par.Add("ApiName", apiName);
            par.Add("HttpMethod", httpMethod);

            int affectedRows = Execute(sql, par);
            ApplicationLog.Debug(string.Format("删除服务元数据；AppId: {0}, ApiName: {1}, HttpMethod: {2}；删除 {3} 条", appId, apiName, httpMethod, affectedRows));

            return affectedRows > 0;
        }
    }
}
